package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;

import com.heima.model.common.constants.admin.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        String date = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        //查询文章列表
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(date);
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 重新计算文章热度  更新redis缓存
     *
     * @param dto
     */
    @Override
    public void updateApArticle(AggBehaviorDTO dto) {
        //1 查询文章
        ApArticle apArticle = apArticleMapper.selectById(dto.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据为空");
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (dto.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? dto.getView() : dto.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (dto.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? dto.getLike() : dto.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (dto.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? dto.getComment() : dto.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (dto.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? dto.getCollect() : dto.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        //执行修改
        apArticleMapper.updateById(apArticle);
        //3 计算文章分值
        Integer score = computeScore(apArticle);
        // 如果是今天发布的文章，热度*3      yyyy-MM-dd
        String publishStr = DateUtils.dateToString(apArticle.getPublishTime());
        String nowStr = DateUtils.dateToString(new Date());
        if (publishStr.equals(nowStr)) {
            score = score * 3;
            //当天热点数据 *3
        }
        //4 更新缓存（频道）
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //5 更新推荐列表的缓存
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 更新文章缓存
     *
     * @param apArticle 当前文章
     * @param score     分数
     * @param cacheKey
     */
    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        //根据缓存的key查询出缓存列表
        String jsonStr = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(jsonStr)) {
            List<HotArticleVo> hotArticleVos = JSON.parseArray(jsonStr, HotArticleVo.class);
            //判断当前文章是否为热点文章
            boolean flag = false;
            for (HotArticleVo hotArticleVo : hotArticleVos) {
                //1 如果当前缓存中有当前文章，更新分值
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }
            //2 缓存中没有当前文章
            if (!flag) {
                HotArticleVo hotArticle = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticle);
                hotArticle.setScore(score);
                hotArticleVos.add(hotArticle);
            }
            //3. 将热点文章集合 按得分降序排序  取前30条缓存至redis中
            hotArticleVos = hotArticleVos.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
        }
    }


    /**
     * 为每一个频道缓存热点较高的30条文章
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //1 查询所有的频道列表
        //远程调用
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<AdChannel> list = responseResult.getData();
        //2 遍历频道列表，筛选当前频道下的文章
        for (AdChannel adChannel : list) {
            //3 给每个频道下的文章进行缓存
            List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                    // 当前频道下的文章列表
                    .filter(hotArticle -> hotArticle.getChannelId().equals(adChannel.getId()))
                    .collect(Collectors.toList());
            sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
        }
        //4 给推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    /**
     * 缓存热点文章
     *
     * @param hotArticleVos
     * @param cacheKey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
        // 对文章进行排序
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算热点文章分值
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        // 定义返回集合
        return articleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            // 2.1计算文章分值算法
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算文章分值算法
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        // 阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
